package com.zhentao.device.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.zhentao.pojo.WaterQualityAnomaly;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;
import java.util.Map;

/**
* @author DELL
* @description 针对表【water_quality_anomaly(水质异常数据表)】的数据库操作Mapper
* @createDate 2025-09-23 10:40:59
* @Entity com.zhentao.pojo.WaterQualityAnomaly
*/
@Mapper
public interface WaterQualityAnomalyMapper extends BaseMapper<WaterQualityAnomaly> {

    /**
     * 根据状态获取告警列表
     */
    @Select("SELECT * FROM water_quality_anomaly WHERE handle_status = #{status} ORDER BY create_time DESC")
    List<WaterQualityAnomaly> selectByStatus(@Param("status") Integer status);

    /**
     * 根据设备ID获取告警列表
     */
    @Select("SELECT * FROM water_quality_anomaly WHERE device_id = #{deviceId} ORDER BY create_time DESC")
    List<WaterQualityAnomaly> selectByDeviceId(@Param("deviceId") String deviceId);

    /**
     * 根据指标代码获取告警列表
     */
    @Select("SELECT * FROM water_quality_anomaly WHERE indicator_code = #{indicator} ORDER BY create_time DESC")
    List<WaterQualityAnomaly> selectByIndicator(@Param("indicator") String indicator);

    /**
     * 更新告警状态
     */
    @Update("UPDATE water_quality_anomaly SET handle_status = #{status} WHERE anomaly_id = #{alertId}")
    int updateStatus(@Param("alertId") Long alertId, @Param("status") Integer status, @Param("handlerId") String handlerId);

    /**
     * 获取告警统计信息
     */
    @Select("SELECT " +
            "COUNT(*) as total, " +
            "SUM(CASE WHEN handle_status = 1 THEN 1 ELSE 0 END) as unhandled, " +
            "SUM(CASE WHEN handle_status = 2 THEN 1 ELSE 0 END) as confirmed, " +
            "SUM(CASE WHEN handle_status = 3 THEN 1 ELSE 0 END) as handled " +
            "FROM water_quality_anomaly")
    Map<String, Object> selectAlertStats();

    /**
     * 批量更新告警状态
     */
    @Update("<script>" +
            "UPDATE water_quality_anomaly SET handle_status = #{status} " +
            "WHERE anomaly_id IN " +
            "<foreach collection='alertIds' item='id' open='(' separator=',' close=')'>" +
            "#{id}" +
            "</foreach>" +
            "</script>")
    int batchUpdateStatus(@Param("alertIds") List<Long> alertIds, @Param("status") Integer status, @Param("handlerId") String handlerId);
}




